package com.chuang.bootplus.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.chuang.bootplus.base.utils.ApiResponse;
import com.chuang.bootplus.base.utils.BeanUtil;
import com.chuang.bootplus.entity.Topic;
import com.chuang.bootplus.entity.TopicComment;
import com.chuang.bootplus.entity.UserInfo;
import com.chuang.bootplus.mapper.TopicCommentMapper;
import com.chuang.bootplus.po.topic.TopicCommentListPO;
import com.chuang.bootplus.po.topic.TopicCommentSavePO;
import com.chuang.bootplus.service.TopicCommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chuang.bootplus.service.UserInfoService;
import com.chuang.bootplus.vo.TopicCommentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2021-08-17
 */
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TopicCommentServiceImpl extends ServiceImpl<TopicCommentMapper, TopicComment> implements TopicCommentService {

    final UserInfoService userInfoService;

    @Override
    public ApiResponse<Void> save(TopicCommentSavePO po) {
        save(BeanUtil.beanA2beanB(po,TopicComment.class));
        return new ApiResponse<>();
    }

    @Override
    public ApiResponse<TopicCommentVO> list(TopicCommentListPO po) {
        Page<TopicComment> topicCommentPage = page(
                new Page<>(po.getPageNumber(),po.getPageSize()),
                new LambdaQueryWrapper<TopicComment>()
                        .eq(po.getParentId()!=null,TopicComment::getParentId,po.getParentId())
                        .eq(po.getTopicId()!=null,TopicComment::getTopicId,po.getTopicId())
        );
        List<TopicCommentVO> topicCommentList = BeanUtil.listA2ListB(topicCommentPage.getRecords(), TopicCommentVO.class);
        for (TopicCommentVO topicCommentVO : topicCommentList) {
            UserInfo userInfo = userInfoService.getById(topicCommentVO.getUserId());
            if(userInfo!=null){
                topicCommentVO.setUserName(userInfo.getNickName());
                topicCommentVO.setUserAvatar(userInfo.getAvatarUrl());
            }
        }
        return new ApiResponse<>(topicCommentList,topicCommentPage.getTotal());
    }
}
